/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CAPA_INTERFAZ_DE_USUARIO;

import CAPA_LOGICA_DE_NEGOCIO.LN_LOGICA_NEGOCIO;
import RECURSOS.FONDO_FORM;
import RECURSOS.LOG;
import RECURSOS.PRODUCTO;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Administrador
 */
public class IU_BUSCAR_PROD_DESCRIPCION extends javax.swing.JFrame {
    private LN_LOGICA_NEGOCIO obj_ln;
    private PRODUCTO objpro;        
    private StringBuilder busqueda;
    private DefaultTableModel modelo;
    private int tecla;        
    private FONDO_FORM F;
        
    
    @Override    
    public Image getIconImage() {
        Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("RECURSOS/SOVI.PNG"));
        return retValue;
    }

    public IU_BUSCAR_PROD_DESCRIPCION() {
        initComponents();
        this.setLocationRelativeTo(null);
        F=new FONDO_FORM(this.getWidth(),this.getHeight()+200,"fondo.png");
        this.add(F);
        this.pack(); 
        this.setLocationRelativeTo(null);
        this.busqueda= new StringBuilder();
        obj_ln=new LN_LOGICA_NEGOCIO();
        objpro=new PRODUCTO();               
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SOVI");
        setIconImage(getIconImage());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTable1.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        jTextField1.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jTextField1.setForeground(new java.awt.Color(0, 0, 102));
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField1KeyTyped(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jButton1.setForeground(new java.awt.Color(0, 0, 102));
        jButton1.setText("AGREGAR");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 0, 102));
        jLabel1.setText("BUSQUEDA");

        jButton2.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jButton2.setForeground(new java.awt.Color(0, 0, 102));
        jButton2.setText("SALIR");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(404, 404, 404)
                        .addComponent(jButton1)
                        .addGap(142, 142, 142)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1034, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(43, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(47, 47, 47)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 438, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(280, 280, 280))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-1135)/2, (screenSize.height-420)/2, 1135, 420);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        IU_FACTURA objfac=new IU_FACTURA();
        boolean repetido=false;
        if(this.jTable1.getSelectedRow()!=-1)
        {
           for (int i = 0; i <objfac.getModelofac().getRowCount() ; i++) {
            //JOptionPane.showMessageDialog(rootPane,String.valueOf(this.jTable1.getModel().getValueAt(i, 2)).indexOf(busqueda.toString()));                            
                if(String.valueOf(objfac.getModelofac().getValueAt(i, 2)).toUpperCase().indexOf(modelo.getValueAt(jTable1.getSelectedRow(), 2).toString().toUpperCase())!=-1)
                {   
                    JOptionPane.showMessageDialog(null,"El producto ya ha sido agregado","ERROR",JOptionPane.ERROR_MESSAGE);
                    repetido=true;
                    break;
                }              
            }
            if(!repetido)            
            {            
                try{                                                        
                    int cantidad=Integer.parseInt(JOptionPane.showInputDialog(null,"CANTIDAD: ","PRODUCTO",JOptionPane.QUESTION_MESSAGE).toString());
                    if(cantidad              
                            <= Integer.parseInt(modelo.getValueAt(jTable1.getSelectedRow(), 1).toString()) && cantidad>0)
                    {                                    

                            Object [] fila = new Object[5];        
                            fila[0]= modelo.getValueAt(jTable1.getSelectedRow(), 0);
                            fila[1]=cantidad;
                            fila[2]= modelo.getValueAt(jTable1.getSelectedRow(), 2);
                            fila[3]= modelo.getValueAt(jTable1.getSelectedRow(), 3);                        
                            fila[4]=Float.parseFloat(modelo.getValueAt(jTable1.getSelectedRow(), 3).toString())*cantidad;

                            modelo.setValueAt((int)Float.parseFloat(modelo.getValueAt(jTable1.getSelectedRow(), 1).toString())-cantidad,jTable1.getSelectedRow(), 1);
                            objfac.getModelofac().addRow(fila);
                            objfac.getModelofac().fireTableDataChanged();
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null,"La cantidad no puede ser mayor a la disponible en stock ni negativa","ERROR",JOptionPane.ERROR_MESSAGE);
                    }
                }
                catch(Exception e)
                {
                    JOptionPane.showMessageDialog(null,"Ingrese una cantidad valida","ERROR",JOptionPane.ERROR_MESSAGE);                
                    System.out.print(e);
                }                
            }            
       }                
       else
       {       
           JOptionPane.showMessageDialog(null,"Seleccione el producto a agregrar","ERROR",JOptionPane.ERROR_MESSAGE);                                    
       }
        //objfac.TablaProductos.setModel(modelo);
        //obj.TablaProductos.setModel(null);       
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped
        char car = evt.getKeyChar();                                 
        //10 es el enter
        if(tecla==10)
        {
            evt.consume();
        }
        else
        {
            //8 es el delete
            if(tecla==8)
            {
                try
                {
                this.busqueda.deleteCharAt(this.busqueda.length()-1);
                }
                catch(Exception e)                    
                {}
                modelo=this.obj_ln.consultar_prodf(objpro);                 
                if(objpro.getError().getDescripcion_error()==null){                
                    this.jTable1.setModel(modelo);        
                }        
                else        
                {//controlar errores            

                }            
            }
            else
            {
                this.busqueda.append(car);
            }

            for (int i = 0; i <this.jTable1.getModel().getRowCount() ; i++) {            

            //JOptionPane.showMessageDialog(rootPane,String.valueOf(this.jTable1.getModel().getValueAt(i, 2)).indexOf(busqueda.toString()));                            
                if(String.valueOf(this.jTable1.getModel().getValueAt(i, 2)).toUpperCase().indexOf(busqueda.toString().toUpperCase())==-1)       
                {   
                    modelo.removeRow(i);
                    i--;
                }              
            }
        }                
        
    }//GEN-LAST:event_jTextField1KeyTyped

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        // TODO add your handling code here:
        tecla=evt.getKeyCode();        
        //37 flecha de la izquierda yn 39 flecha derecha
        if(tecla==37 || tecla== 39)
        {
            evt.consume();
        }
    }//GEN-LAST:event_jTextField1KeyPressed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        
        
        modelo=this.obj_ln.consultar_prodf(objpro);                        
        if(objpro.getError().getDescripcion_error()==null){        
            this.jTable1.setModel(modelo);
        }
        else
        {
             LOG l=new LOG();
             JOptionPane.showMessageDialog(null,obj_ln.error_usuario(objpro.getError()),"ERROR",JOptionPane.ERROR_MESSAGE);
             String log="Tipo: "+objpro.getError().getTipo_error()+". Mensaje: "+objpro.getError().getDescripcion_error();             
             l.escribir(log);                          
             this.dispose();
        }                
    }//GEN-LAST:event_formWindowOpened

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IU_BUSCAR_PROD_DESCRIPCION.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IU_BUSCAR_PROD_DESCRIPCION.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IU_BUSCAR_PROD_DESCRIPCION.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IU_BUSCAR_PROD_DESCRIPCION.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new IU_BUSCAR_PROD_DESCRIPCION().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
